package com.chookss;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.noonesdk.PushInitConfig;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.aliyun.sys.AlivcSdkCore;
import com.baidu.location.LocationClient;
import com.baidu.mobstat.StatService;
import com.bun.miitmdid.core.JLibrary;
import com.chookss.base.AppStatusManager;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.FileEntity;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.OkGoConfig;
import com.hjq.toast.ToastUtils;
import com.johnrambo.ktea.Settings;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.johnrambo.ktea.net.http.JsonStyle;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.OkDownload;
import com.liulishuo.okdownload.core.file.CustomProcessFileStrategy;
import com.meituan.android.walle.WalleChannelReader;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsDownloader;
import com.tencent.smtt.sdk.TbsListener;
import com.tencent.tbs.reader.ITbsReader;
import com.tencent.tbs.reader.ITbsReaderCallback;
import com.tencent.tbs.reader.TbsFileInterfaceImpl;
import com.zxy.tiny.Tiny;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.internal.Intrinsics;


public class MyApp extends Application {

    public static LinkedList<Activity> activitys = new LinkedList();
    public static Context appCtx;
    public static Application appSettingCtx;
    public static HashMap<String, DownloadTask> downloadTaskHashMap = new HashMap<String, DownloadTask>();
    public static List<String> downloadFiles = new ArrayList<>();
    public static Boolean TokenStatus = false;//token已经失效，是否进入登录页面
    public static Boolean isSplash = false;//默认没有开启启动页，只能存在一个
    public static Boolean docunmentOpen = false;//文档只能同时被打开一个
    public static boolean mIsInitTBSSuccess = false;  //是否x5成功了
    public static String accessKeyId = ""; //视频上传所需
    public static String accessKeySecret = "";
    public static boolean isDownApk = false;//下载中
    public static boolean THEME = false;//是否变灰
    public static int longVideoEvery = 60; // 长视频每60秒时扣除一次流量
    public static int smalVideoEvery = 60; // 短视频每60秒时扣除一次流量
    public static int dragPlay = 0; // 代表内容播放开始几秒钟后扣除
    public static int startPlay = 1; // 短视频每60秒时扣除一次流量
    public static String PUSHID = "";// 阿里云设备推送id
    public static boolean mIsInitPUSHSuccess = false;  //是否推送初始化成功了
    public static List<ContactEntity> contactEntityLogList = new ArrayList<>();//日志选择临时存储
    public static List<KnowledgeEntity> videoFolderList = new ArrayList<>();//视频目录选择
    public static Map<String, String> videoFolderMap = new HashMap();//视频目录选择
    public static boolean uploadRecordStatus = false;//上传中心是否有上传任务
    public static boolean uploadLogStatus = false;//日志中心是否有上传任务
    public static boolean uploadHolidayStatus = false;//请假是否有上传任务
    public static boolean privacyPermissions = false;//是否有隐私权限
    public static FileEntity fileEntity = null;//报销类型选择


    //打生产包，只需要改MyApp Klog
    @Override
    public void onCreate() {
        super.onCreate();
        appCtx = this;
        appSettingCtx =this;
        setAppSetting("");
        ToastUtils.init(appSettingCtx);
        AppStatusManager.init(appSettingCtx);
        if (!new ShareUtils().getBoolean(appCtx, StaticClass.SHARE_IS_FIRST, true)) {
            init();
        }
    }

    public static void init() {
        MyApp.privacyPermissions = true;
        KLog.init(false, "jia");
        PushInitConfig config = null;
        if(Urls.baseUrl.contains("dev")){
            //测试环境
            config = new PushInitConfig.Builder()
                    .application(appSettingCtx)
                    .appKey("333495890")
                    .appSecret("745985d1a3434f4b81adec9b40c43a66")
                    .build();
        }else{
            //生产环境
            if (appCtx.getPackageName().equals("com.zhaofengnum")) {
                config = new PushInitConfig.Builder()
                        .application(appSettingCtx)
                        .appKey("333855039")
                        .appSecret("51eb7f87b0cb4df8b971bbb28492d333")
                        .build();
            } else {
                config = new PushInitConfig.Builder()
                        .application(appSettingCtx)
                        .appKey("333522707")
                        .appSecret("f180f050a3b74ba69e20de1bf29271db")
                        .build();
            }
        }
        PushServiceFactory.init(config);
        StatService.setAuthorizedState(appCtx, false);
        Tiny.getInstance().init(appSettingCtx);
        try {
            OkDownload.setSingletonInstance(
                    new OkDownload.Builder(appCtx)
                            .processFileStrategy(new CustomProcessFileStrategy())
                            .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        initOkgoBugly();
        initCloudChannel();
        initBaiduCount();
        //短视频sdk，暂时只支持api 18以上的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            AlivcSdkCore.register(appSettingCtx);
            AlivcSdkCore.setLogLevel(AlivcSdkCore.AlivcLogLevel.AlivcLogDebug);
        }
    }

    /**
     * 初始化百度统计 和地图
     */
    public static void initBaiduCount() {
        if (appCtx.getPackageName().equals("com.zhaofengnum")) {
            LocationClient.setKey("z9CAs2oeGukhpWRjjNSc1QhjfuBR0Pbv");
            StatService.setAppKey("d4cb2a53b8");
        } else {
            LocationClient.setKey("9GpY0wlDfr410bR3FuVmgvPRqlYfXKlC");
            StatService.setAppKey("kq02FGECmbSHQuCuqDMqDQxGqpWXQXAs");
        }
        String channel;
        try {
            channel = WalleChannelReader.getChannel(appCtx);
            StatService.setAppChannel(appCtx, channel, true);
            // 打开崩溃收集
            StatService.setOn(appCtx, StatService.EXCEPTION_LOG);
            StatService.enableDeviceMac(appCtx, false);
            JLibrary.InitEntry(appCtx);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setAppSetting(String token) {
        String newToken = token;
        if (Utils.isNull(newToken)) {
            newToken = new ShareUtils().getString(MyApp.appCtx, StaticClass.TOKEN, "");
        }
        String finalNewToken = newToken;
        Settings.Companion.init((Function1) (new Function1() {
            // $FF: synthetic method
            // $FF: bridge method
            public Object invoke(Object var1) {
                this.invoke((Settings) var1);
                return Unit.INSTANCE;
            }

            public final void invoke(@NotNull Settings $this$init) {
                Intrinsics.checkNotNullParameter($this$init, "$receiver");
                $this$init.setAppCtx(appSettingCtx);
                $this$init.setBaseUrl(Urls.baseUrl);
                $this$init.setWebsocketurl("");
                $this$init.setActivityStack(activitys);
                $this$init.setVersionName(new ShareUtils().getString(MyApp.appCtx, StaticClass.VERSIONNAME, ""));
                $this$init.setToken(finalNewToken);
                $this$init.setDEBUG(false);
                JsonStyle var2 = new JsonStyle();
                var2.setStatusName("code");
                var2.setDataName("data");
                var2.setMessageName("msg");
                var2.setSuccessStatusValue("200");
                var2.setTokenLoseStatusValue("4000");
                $this$init.setObjectStyle(var2);
            }
        }));
    }

    public static void initOkgoBugly() {
        OkGoConfig.init(appSettingCtx, "", "");

    }

    /**
     * 初始化云推送通道
     */

    public static void initCloudChannel() {
        // 获取隐私政策签署状态
        boolean sign = new ShareUtils().getBoolean(appSettingCtx, StaticClass.ISLOGIN, false);
        createNotificationChannel();
        if (sign) {
            mIsInitPUSHSuccess = true;
            CloudPushService pushService = PushServiceFactory.getCloudPushService();
            pushService.setLogLevel(CloudPushService.LOG_DEBUG);
            pushService.register(appSettingCtx, new CommonCallback() {
                @Override
                public void onSuccess(String response) {
                    PUSHID = pushService.getDeviceId();
                    if (!Utils.isNull(PUSHID)) {
                        new ShareUtils().putString(appSettingCtx, StaticClass.PUSHID, PUSHID);
                    }
                    Log.d("MyMessageReceiver", "init cloudchannel success   " + pushService.getDeviceId());
                }

                @Override
                public void onFailed(String errorCode, String errorMessage) {
                    Log.d("MyMessageReceiver", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
                }
            });
            if (appCtx.getPackageName().equals("com.zhaofengnum")) {
                MiPushRegister.register(appSettingCtx, "2882303761520248956", "5672024820956"); // 初始化小米辅助推送
                HuaWeiRegister.register(appSettingCtx); // 接入华为辅助推送
//        VivoRegister.register(appSettingCtx);
                OppoRegister.register(appSettingCtx, "97f57d1dd692420196c7fa72d34183db", "7a8fce29ddb04887a0f17b749dc6a21f");
//                MeizuRegister.register(appSettingCtx, "143945", "62260dbff2e1402990cdf0f0b4db7564");
            } else {
                MiPushRegister.register(appSettingCtx, "2882303761520021711", "5702002126711"); // 初始化小米辅助推送
                HuaWeiRegister.register(appSettingCtx); // 接入华为辅助推送
//        VivoRegister.register(appSettingCtx);
                OppoRegister.register(appSettingCtx, "03ada38a10e244759392ee0273f45cb0", "3d0fa0cfbe1146308e140bca3396e19e");
//                MeizuRegister.register(appSettingCtx, "143945", "62260dbff2e1402990cdf0f0b4db7564");
            }
        }
    }

    public static void initX5() {
        try {
            // 在调用TBS初始化、创建WebView之前进行如下配置
            HashMap map = new HashMap();
            map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
            map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
            QbSdk.initTbsSettings(map);

        } catch (Exception e) {
            e.printStackTrace();
        }
        QbSdk.setDownloadWithoutWifi(true);//非wifi条件下允许下载X5内核
        QbSdk.setTbsListener(
                new TbsListener() {
                    @Override
                    public void onDownloadFinish(int i) {
                        //下载结束时的状态，下载成功时errorCode为100,其他均为失败，外部不需要关注具体的失败原因
                        KLog.i("onViewInitFinished-onDownloadFinish -->下载X5内核完成：" + i);
                        if (i == 100) {
//                            mIsInitTBSSuccess = true;
                        }
                    }

                    @Override
                    public void onInstallFinish(int i) {
                        //安装结束时的状态，安装成功时errorCode为200,其他均为失败，外部不需要关注具体的失败原因
                        KLog.i("onViewInitFinished-onInstallFinish -->安装X5内核进度：" + i);
                    }

                    @Override
                    public void onDownloadProgress(int i) {
                        //下载过程的通知，提供当前下载进度[0-100]
                        KLog.i("onViewInitFinished-onDownloadProgress -->下载X5内核进度：" + i);
                    }
                });
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，
//                否则表示x5内核加载失败，会自动切换到系统内核。
//                mIsInitTBSSuccess = arg0;
                KLog.i(" onViewInitFinished is " + arg0);
                if (!arg0) {
                    TbsDownloader.startDownload(appSettingCtx);
                }
            }

            @Override
            public void onCoreInitFinished() {
            }
        };

        QbSdk.initX5Environment(appCtx, cb);
        if (!QbSdk.isTbsCoreInited()) {
            QbSdk.preInit(appCtx, cb);
        }
        File SDRootPath = new File(appSettingCtx.getFilesDir() + "/TbsReaderTemp");
        if (!SDRootPath.exists()) {
            // 按照指定的路径创建文件夹
            SDRootPath.mkdirs();
        }
        //设置licenseKey
        TbsFileInterfaceImpl.setLicenseKey("xvyybfJcBXGf3M1XOQCeCd40PtfXr/ZTCTcDRCWOG0I=");
        if (!TbsFileInterfaceImpl.isEngineLoaded()) {
            TbsFileInterfaceImpl.initEngineAsync(appCtx, new ITbsReaderCallback() {
                @Override
                public void onCallBackAction(Integer integer, Object o, Object o1) {
                    if (ITbsReader.OPEN_FILEREADER_ASYNC_LOAD_READER_ENTRY_CALLBACK == integer) {
                        int ret = (int) o; // 错误码为actionType == 7002时 args的值
                        KLog.i(" onViewInitFinished TbsFileInterfaceImpl is " + ret);
                        if (ret == 0) {
                            // 初始化成功
                            mIsInitTBSSuccess = true;
                        } else {
                            // 初始化失败
                            mIsInitTBSSuccess = false;
                        }
                        KLog.i(ret + "===");
                    }
                }
            });
        }
    }

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                layout.setReboundDuration(100);
                return new MaterialHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    public static void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) appSettingCtx.getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "1";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "推送";
            // 用户可以看到的通知渠道的描述
            String description = appCtx.getResources().getString(R.string.app_name) + "消息推送";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            //振动
            mChannel.enableVibration(true);
            Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mChannel.setSound(uri, Notification.AUDIO_ATTRIBUTES_DEFAULT);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            // 配置通知渠道的属性
            mChannel.setDescription(description);

            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }

    /**
     * 退出所有activity
     */
    public static void exitApp() {
        try {
            NotificationManager mgr = (NotificationManager) appSettingCtx.getSystemService(Context.NOTIFICATION_SERVICE);
            mgr.cancelAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < activitys.size(); i++) {
            activitys.get(i).finish();
        }
        activitys.clear();
//        try {
//            ActivityManager activityMgr = (ActivityManager) appCtx
//                    .getSystemService(Context.ACTIVITY_SERVICE);
//            activityMgr.restartPackage(appCtx.getPackageName());
//            System.exit(0);
//        } catch (Exception e) {
//        }
    }
}
